from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework import status
from alipay import AliPay
from django.conf import settings
import os

from orders.models import OrderInfo
from .models import Payment


# Create your views here.
class PaymentView(APIView):
    """生成支付宝链接"""
    # 指定权限
    permission_classes = [IsAuthenticated]

    def get(self, request, order_id):

        # 1.校验订单
        try:
            order = OrderInfo.objects.get(order_id=order_id, user=request.user,
                                          status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'])
        except OrderInfo.DoesNotExist:
            return Response({'message': '订单信息有误'}, status=status.HTTP_400_BAD_REQUEST)

        # 2.利用支付宝sdk 创建支付对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,  # 当前用的是沙盒应用的,将来公司支付宝应用申请下来后,换掉
            app_notify_url=None,  # 默认回调url
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keys/app_private_key.pem'),
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                'keys/alipay_pubilc_key.pem'),
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=settings.ALIPAY_DEBUG  # 默认False
        )

        # 3.调用api_alipay_trade_page_pay,生成支付链接后面的查询参数
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,  # 要支付的订单编号
            total_amount=str(order.total_amount),  # 一定要把总总金额转换成字符串
            subject='美多商城:%s' % order_id,
            return_url="http://www.meiduo.site:8080/pay_success.html"  # 支付成功后的回调页面
        )

        # 4. 拼接真实环境支付连接: https://openapi.alipay.com/gateway.do? + order_string
        # 拼接沙箱环境支付连接: https://openapi.alipaydev.com/gateway.do? + order_string
        alipay_url = settings.ALIPAY_URL + '?' + order_string

        return Response({"alipay_url": alipay_url})


class PaymentStatusView(APIView):
    """修改定单状态及把订单编号和支付宝交易号绑定"""

    def put(self, request):

        # 获取查询参数数据
        queryDict = request.query_params
        # 将QueryDict类型对象转换成dict
        data = queryDict.dict()
        # 再将sign 数据从dict字典中移除
        sign = data.pop('sign')

        # 创建alipay对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,  # 当前用的是沙盒应用的,将来公司支付宝应用申请下来后,换掉
            app_notify_url=None,  # 默认回调url
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keys/app_private_key.pem'),
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                'keys/alipay_pubilc_key.pem'),
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=settings.ALIPAY_DEBUG  # 默认False
        )

        # 使用alipay调用verify方法进行校验支付信息
        success = alipay.verify(data, sign)
        if success:
            # 订单编号和支付宝交易号绑定
            order_id = data.get('out_trade_no')  # 获取美多订单编号
            trade_id = data.get('trade_no')  # 获取支付宝交易号
            Payment.objects.create(
                order_id=order_id,
                trade_id=trade_id
            )

            # 修改当前美多商城订单状态
            OrderInfo.objects.filter(order_id=order_id, status=OrderInfo.ORDER_STATUS_ENUM['UNPAID']).update(status=OrderInfo.ORDER_STATUS_ENUM['UNSEND'])
            # 响应 支付宝交易号
            return Response({'trade_id': trade_id})
        else:
            return Response({'message': '非法请求'}, status=status.HTTP_403_FORBIDDEN)

